package com.mintcode.ssh.daoimpl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionFactory {
	private static final String CFG_FILE_LOCATION = "/Hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static final Configuration cfg = new Configuration()
			.configure(CFG_FILE_LOCATION);
	private static ServiceRegistryBuilder builder = new ServiceRegistryBuilder()
			.applySettings(cfg.getProperties());
	private static ServiceRegistry registry;
	private static SessionFactory sessionFactory;

	public static Session currenSession() throws HibernateException {
		Session session = threadLocal.get();
		if (null == session || false == session.isOpen()) {
			if (null == sessionFactory) {
				try {
					registry = builder.buildServiceRegistry();
					sessionFactory = cfg.buildSessionFactory(registry);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			session = sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}

	public static void closeSession() throws HibernateException {
		Session session = threadLocal.get();
		threadLocal.set(null);
		if (null != session) {
			session.close();
		}
	}
}
